<?php
/**
 * Created by PhpStorm.
 * User: sunlight
 * Date: 2018/11/26
 * Time: 12:21
 */

namespace app\api\controller\V1;

use app\api\controller\Common;
use app\common\lib\Aes;
use app\common\lib\IAuth;

class Login extends Common{

    /**
     * 生成账号
     * @return \think\response\Json
     */
    public function save(){
        if (!request()->isPost()){
            return show(config('code.error'),'你没有权限','',403);
        }

        $param=input('param.');
//halt($param);
        if ($param['account_num']==0){
            return show(config('code.error'),'你未消费，无生成账号权限，请先消费！！','',404);
        }else if ($param['account_num']==4){
            return show(config('code.error'),'你已达到生成账号上线，请在此消费后在进行使用','',404);
        }

        if (empty($param['phone'])){
            return show(config('code.error'),'手机号不合法','',404);
        }

        if (empty($param['email'])){
            return show(config('code.error'),'邮箱不合法','',403);
        }

        $token=IAuth::setAppLoginToken($param['phone']);
        //第一次登陆
        $data=[
            'token' => $token,
            'time_out' =>strtotime("+".config('app.login_time_out_day')." days"),
            'username' => 'ym'.$param['phone'],
            'password' => uniqid('ym'),
            'status' =>1,
            'phone' =>$param['phone'],
            'email' => $param['email'],
            'image' => '/img/5174512.png',
        ];

        $id=model('User')->add($data);

        $obj=new Aes();
        if ($id){
            $result=[
                'token' => $obj->encrypt($token."||".$id),
            ];
            return show(config('code.success'),'ok',$result,200);
        }

    }

    /**
     * 用户登陆
     */
    public function login(){
        if (!request()->isPost()){
            return show(config('code.error'),'你没有权限','',403);
        }

        $param=input('param.');

        if (empty($param['phone'])){
            return show(config('code.error'),'手机号不合法','',404);
        }

        try{
            //判断是否用户名密码合法
            $user=model('User')->get(['phone' => $param['phone']]);
        }catch (Exception $e){
            $this->error($e->getMessage());
        }

        if (!$user || $user->status!=config('code.status_normal')){
            $this->error('该用户不存在');
        }

        $token = IAuth::setAppLoginToken($param['phone']);
        $data=[
            'token' => $token,
            'time_out' => strtotime("+".config('app.login_time_out_day')." days"),

        ];

        if ($user && $user->status==1){
            $id=model('User')->save($data, ['phone' => $param['phone']]);
        }

        $obj=new Aes();
        if ($id){
            $result=[
                'token' => $obj->encrypt($token."||".$id),
                'id' => $id
            ];
            return show(config('code.success'), 'ok', $result,200);
        }else{
            return show(config('code.error'), '登录失败', [], 403);
        }
    }

}